<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License. 
-->
<html>
<head>
    <link type="text/css" rel="stylesheet" href="https://struts.apache.org/css/default.css">
    <style type="text/css">
        .dp-highlighter {
            width:95% !important;
        }
    </style>
    <style type="text/css">
        .footer {
            background-image:      url('https://cwiki.apache.org/confluence/images/border/border_bottom.gif');
            background-repeat:     repeat-x;
            background-position:   left top;
            padding-top:           4px;
            color:                 #666;
        }
    </style>
    <link href='https://struts.apache.org/highlighter/style/shCoreStruts.css' rel='stylesheet' type='text/css' />
    <link href='https://struts.apache.org/highlighter/style/shThemeStruts.css' rel='stylesheet' type='text/css' />
    <script src='https://struts.apache.org/highlighter/js/shCore.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushPlain.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushXml.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJava.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushJScript.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushGroovy.js' type='text/javascript'></script>
    <script src='https://struts.apache.org/highlighter/js/shBrushBash.js' type='text/javascript'></script>
    <script type="text/javascript">
        SyntaxHighlighter.defaults['toolbar'] = false;
        SyntaxHighlighter.all();
    </script>
    <script type="text/javascript" language="javascript">
        var hide = null;
        var show = null;
        var children = null;

        function init() {
            /* Search form initialization */
            var form = document.forms['search'];
            if (form != null) {
                form.elements['domains'].value = location.hostname;
                form.elements['sitesearch'].value = location.hostname;
            }

            /* Children initialization */
            hide = document.getElementById('hide');
            show = document.getElementById('show');
            children = document.all != null ?
                    document.all['children'] :
                    document.getElementById('children');
            if (children != null) {
                children.style.display = 'none';
                show.style.display = 'inline';
                hide.style.display = 'none';
            }
        }

        function showChildren() {
            children.style.display = 'block';
            show.style.display = 'none';
            hide.style.display = 'inline';
        }

        function hideChildren() {
            children.style.display = 'none';
            show.style.display = 'inline';
            hide.style.display = 'none';
        }
    </script>
    <title>REST Plugin</title>
</head>
<body onload="init()">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
    <tr class="topBar">
        <td align="left" valign="middle" class="topBarDiv" align="left" nowrap>
            &nbsp;<a href="home.html">Home</a>&nbsp;&gt;&nbsp;<a href="guides.html">Guides</a>&nbsp;&gt;&nbsp;<a href="plugin-developers-guide.html">Plugin Developers Guide</a>&nbsp;&gt;&nbsp;<a href="rest-plugin.html">REST Plugin</a>
        </td>
        <td align="right" valign="middle" nowrap>
            <form name="search" action="https://www.google.com/search" method="get">
                <input type="hidden" name="ie" value="UTF-8" />
                <input type="hidden" name="oe" value="UTF-8" />
                <input type="hidden" name="domains" value="" />
                <input type="hidden" name="sitesearch" value="" />
                <input type="text" name="q" maxlength="255" value="" />
                <input type="submit" name="btnG" value="Google Search" />
            </form>
        </td>
    </tr>
</table>

<div id="PageContent">
    <div class="pageheader" style="padding: 6px 0px 0px 0px;">
        <!-- We'll enable this once we figure out how to access (and save) the logo resource -->
        <!--img src="/wiki/images/confluence_logo.gif" style="float: left; margin: 4px 4px 4px 10px;" border="0"-->
        <div style="margin: 0px 10px 0px 10px" class="smalltext">Apache Struts 2 Documentation</div>
        <div style="margin: 0px 10px 8px 10px"  class="pagetitle">REST Plugin</div>

        <div class="greynavbar" align="right" style="padding: 2px 10px; margin: 0px;">
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=70699">
                <img src="https://cwiki.apache.org/confluence/images/icons/notep_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Edit Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/editpage.action?pageId=70699">Edit Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">
                <img src="https://cwiki.apache.org/confluence/images/icons/browse_space.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Browse Space"></a>
            <a href="https://cwiki.apache.org/confluence/pages/listpages.action?key=WW">Browse Space</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=70699">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_page_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add Page"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createpage.action?spaceKey=WW&fromPageId=70699">Add Page</a>
            &nbsp;
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=70699">
                <img src="https://cwiki.apache.org/confluence/images/icons/add_blogentry_16.gif"
                     height="16" width="16" border="0" align="absmiddle" title="Add News"></a>
            <a href="https://cwiki.apache.org/confluence/pages/createblogpost.action?spaceKey=WW&fromPageId=70699">Add News</a>
        </div>
    </div>

    <div class="pagecontent">
        <div class="wiki-content">
            <div id="ConfluenceContent"><div class="confluence-information-macro confluence-information-macro-information"><span class="aui-icon aui-icon-small aui-iconfont-info confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>This plugin is only available with Struts 2.1.1 or later</p></div></div><p><style type="text/css">/*<![CDATA[*/
div.rbtoc1440489225220 {padding: 0px;}
div.rbtoc1440489225220 ul {list-style: disc;margin-left: 0px;}
div.rbtoc1440489225220 li {margin-left: 0px;padding-left: 0px;}

/*]]>*/</style></p><div class="toc-macro rbtoc1440489225220">
<ul class="toc-indentation"><li><span class="TOCOutline">1</span> <a shape="rect" href="#RESTPlugin-Overview">Overview</a>
<ul class="toc-indentation"><li><span class="TOCOutline">1.1</span> <a shape="rect" href="#RESTPlugin-Features">Features</a></li><li><span class="TOCOutline">1.2</span> <a shape="rect" href="#RESTPlugin-MappingRESTURLstoStruts2Actions">Mapping REST URLs to Struts 2 Actions</a>
<ul class="toc-indentation"><li><span class="TOCOutline">1.2.1</span> <a shape="rect" href="#RESTPlugin-RESTfulURLMappingLogic">RESTful URL Mapping Logic</a></li></ul>
</li><li><span class="TOCOutline">1.3</span> <a shape="rect" href="#RESTPlugin-ContentTypes">Content Types</a></li></ul>
</li><li><span class="TOCOutline">2</span> <a shape="rect" href="#RESTPlugin-Usage">Usage</a>
<ul class="toc-indentation"><li><span class="TOCOutline">2.1</span> <a shape="rect" href="#RESTPlugin-SettingUp">Setting Up</a>
<ul class="toc-indentation"><li><span class="TOCOutline">2.1.1</span> <a shape="rect" href="#RESTPlugin-Configuration(struts.xml)">Configuration ( struts.xml )</a>
<ul class="toc-indentation"><li><span class="TOCOutline">2.1.1.1</span> <a shape="rect" href="#RESTPlugin-RESTOnlyConfiguration">REST Only Configuration</a></li><li><span class="TOCOutline">2.1.1.2</span> <a shape="rect" href="#RESTPlugin-RESTandnon-RESTfulURL'sTogetherConfiguration">REST and non-RESTful URL's Together Configuration</a></li></ul>
</li></ul>
</li><li><span class="TOCOutline">2.2</span> <a shape="rect" href="#RESTPlugin-WriteYourControllerActions">Write Your Controller Actions</a></li></ul>
</li><li><span class="TOCOutline">3</span> <a shape="rect" href="#RESTPlugin-AdvancedTopics">Advanced Topics</a>
<ul class="toc-indentation"><li><span class="TOCOutline">3.1</span> <a shape="rect" href="#RESTPlugin-CustomContentTypeHandlers">Custom ContentTypeHandlers</a></li><li><span class="TOCOutline">3.2</span> <a shape="rect" href="#RESTPlugin-UseJacksonframeworkasJSONContentTypeHandler">Use Jackson framework as JSON ContentTypeHandler</a></li><li><span class="TOCOutline">3.3</span> <a shape="rect" href="#RESTPlugin-Settings">Settings</a></li></ul>
</li><li><span class="TOCOutline">4</span> <a shape="rect" href="#RESTPlugin-Resources">Resources</a></li><li><span class="TOCOutline">5</span> <a shape="rect" href="#RESTPlugin-VersionHistory">Version History</a></li></ul>
</div><h2 id="RESTPlugin-Overview">Overview</h2><p>The REST Pluginprovides high level support for the implementation of RESTful resource based web applicationsThe REST plugin can cooperate with the <a shape="rect" href="convention-plugin.html">Convention Plugin</a> to support a zero configuration approach to declaring your actions and results, but you can always use the REST plugin with XML style configuration if you like.</p><p>If you prefer to see a working code example, instead of reading through an explanation, you can download the <a shape="rect" class="external-link" href="http://struts.apache.org/2.x/index.html">struts2 sample apps</a> and check out the <code>struts2-rest-showcase</code> application, a complete WAR file, that demonstrates a simple REST web program.</p><h3 id="RESTPlugin-Features">Features</h3><ul><li>Ruby on Rails REST-style URLs</li><li>Zero XML config when used with Convention Plugin</li><li>Built-in serialization and deserialization support for XML and JSON</li><li>Automatic error handling</li><li>Type-safe configuration of the HTTP response</li><li>Automatic conditional GET support</li></ul><h3 id="RESTPlugin-MappingRESTURLstoStruts2Actions">Mapping REST URLs to Struts 2 Actions</h3><p>The main functionality of the REST plugin lies in the interpretation of incoming request URL's according the RESTful rules. In the Struts 2 framework, this 'mapping' of request URL's to Actions is handled by in implementation of the <a shape="rect" class="external-link" href="http://struts.apache.org/2.x/struts2-core/apidocs/org/apache/struts2/dispatcher/mapper/ActionMapper.html"><code>ActionMapper</code></a> interface. Out of the box, Struts 2 uses the <a shape="rect" class="external-link" href="http://struts.apache.org/2.x/struts2-core/apidocs/org/apache/struts2/dispatcher/mapper/DefaultActionMapper.html"><code>DefaultActionMapper</code></a> to map URL's to Actions via the logic you are probably already familiar with.</p><div class="confluence-information-macro confluence-information-macro-note"><span class="aui-icon aui-icon-small aui-iconfont-warning confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p><em>Actions or Controllers</em>? Most Struts 2 developers are familiar with the Action. They are the things that get executed by the incoming requests. In the context of the REST plugin, just to keep you on your toes, we'll adopt the RESTful lingo and refer to our Actions as <em>Controllers</em>. Don't be confused; it's just a name!</p></div></div><p>The REST plugin provides an alternative implementation, <a shape="rect" class="external-link" href="http://struts.apache.org/2.x/struts2-plugins/struts2-rest-plugin/apidocs/org/apache/struts2/rest/RestActionMapper.html"><code>RestActionMapper</code></a>, that provides the RESTful logic that maps a URL to a give action class ( aka 'controller' in RESTful terms ) and, more specifically, to the invocation of a method on that controller class. The following section, which comes from the Javadoc for the class, details this logic.</p><h4 id="RESTPlugin-RESTfulURLMappingLogic">RESTful URL Mapping Logic</h4><p>This Restful action mapper enforces Ruby-On-Rails REST-style mappings. If the method is not specified (via '!' or 'method:' prefix), the method is "guessed" at using REST-style conventions that examine the URL and the HTTP method. Special care has&#160;been given to ensure this mapper works correctly with the codebehind plugin so that&#160;XML configuration is unnecessary.</p><p>This mapper supports the following parameters:</p><ul style="list-style-type: square;"><li><span style="line-height: 1.4285715;"><code>struts.mapper.idParameterName</code> - If set, this value will be the name</span><span style="line-height: 1.4285715;">&#160;of the parameter under which the id is stored. The id will then be removed</span><span style="line-height: 1.4285715;">&#160;from the action name. Whether or not the method is specified, the mapper will&#160;</span><span style="line-height: 1.4285715;">&#160;try to truncate the identifier from the url and store it as a parameter.</span></li><li><span style="line-height: 1.4285715;"><code>struts.mapper.indexMethodName</code> - The method name to call for a GET</span><span style="line-height: 1.4285715;">&#160;request with no id parameter. Defaults to <strong>index</strong>.</span></li><li><span style="line-height: 1.4285715;"><code>struts.mapper.getMethodName</code> - The method name to call for a GET</span><span style="line-height: 1.4285715;">&#160;request with an id parameter. Defaults to <strong>show</strong>.</span></li><li><span style="line-height: 1.4285715;"><code>struts.mapper.postMethodName</code> - The method name to call for a POST</span><span style="line-height: 1.4285715;">&#160;request with no id parameter. Defaults to <strong>create</strong>.</span></li><li><span style="line-height: 1.4285715;"><code>struts.mapper.putMethodName</code> - The method name to call for a PUT</span><span style="line-height: 1.4285715;">&#160;request with an id parameter. Defaults to <strong>update</strong>.</span></li><li><span style="line-height: 1.4285715;"><code>struts.mapper.deleteMethodName</code> - The method name to call for a DELETE</span><span style="line-height: 1.4285715;">&#160;request with an id parameter. Defaults to <strong>destroy</strong>.</span></li><li><span style="line-height: 1.4285715;"><code>struts.mapper.editMethodName</code> - The method name to call for a GET</span><span style="line-height: 1.4285715;">&#160;request with an id parameter and the <strong>edit</strong>&#160;view specified. Defaults to <strong>edit</strong>.</span></li><li><span style="line-height: 1.4285715;"><code>struts.mapper.newMethodName</code> - The method name to call for a GET</span><span style="line-height: 1.4285715;">&#160;request with no id parameter and the <strong>new</strong>&#160;view specified. Defaults to <strong>editNew</strong>.</span></li></ul><p>The following URL's will invoke its methods:</p><ul style="list-style-type: square;"><li><code>GET: /movies</code>&#160;=&gt; method=<strong>index</strong></li><li><span style="line-height: 1.4285715;"><code>GET: /movies/Thrillers</code>&#160;=&gt; method=<strong>show</strong>, id=<strong>Thrillers</strong></span></li><li><span style="line-height: 1.4285715;"><code>GET: /movies/Thrillers;edit</code>&#160;=&gt; method=<strong>edit</strong>, id=<strong>Thrillers</strong></span></li><li><span style="line-height: 1.4285715;"><code>GET: /movies/Thrillers/edit</code>&#160;=&gt; method=<strong>edit</strong>, id=<strong>Thrillers</strong></span></li><li><span style="line-height: 1.4285715;"><code>GET: /movies/new</code>&#160;=&gt; method=<strong>editNew</strong></span></li><li><span style="line-height: 1.4285715;"><code>POST: /movies</code> =&gt; method=<strong>create</strong></span></li><li><span style="line-height: 1.4285715;"><code>PUT: /movies/Thrillers</code>&#160;=&gt; method=<strong>update</strong>, id=<strong>Thrillers</strong></span></li><li><span style="line-height: 1.4285715;"><code>DELETE: /movies/Thrillers</code>&#160;=&gt; method=<strong>destroy</strong>, id=<strong>Thrillers</strong></span></li></ul><div class="confluence-information-macro confluence-information-macro-note"><span class="aui-icon aui-icon-small aui-iconfont-warning confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>To simulate the HTTP methods PUT and DELETE, since they aren't supported by HTML,&#160;the HTTP parameter "_method" will be used.</p></div></div><p>Or, expressed as a table:</p><div class="table-wrap"><table class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1" class="confluenceTh"><p>HTTP method</p></th><th colspan="1" rowspan="1" class="confluenceTh"><p>URI</p></th><th colspan="1" rowspan="1" class="confluenceTh"><p>Class.method</p></th><th colspan="1" rowspan="1" class="confluenceTh"><p>parameters</p></th></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>GET</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>/movie</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Movie.index</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>&#160;</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>POST</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>/movie</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Movie.create</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>&#160;</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>PUT</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>/movie/Thrillers</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Movie.update</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>id="Thrillers"</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>DELETE</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>/movie/Thrillers</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Movie.destroy</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>id="Thrillers"</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>GET</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>/movie/Thrillers</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Movie.show</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>id="Thrillers"</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>GET</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>/movie/Thrillers/edit</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Movie.edit</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>id="Thrillers"</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p>GET</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>/movie/new</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Movie.editNew</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>&#160;</p></td></tr></tbody></table></div><h3 id="RESTPlugin-ContentTypes">Content Types</h3><p>In addition to providing mapping of RESTful URL's to Controller ( Action ) invocations, the REST plugin also provides the ability to produce multiple representations of the resource data. By default, the plugin can return the resource in the following content types:</p><ul style="list-style-type: square;"><li>HTML</li><li><span style="line-height: 1.4285715;">XML&#160;</span></li><li><span style="line-height: 1.4285715;">JSON</span></li></ul><p>There is nothing configure here, just add the conent type extension to your RESTful URL. The framework will take care of the rest. So, for instance, assuming a Controller called Movies and a movie with the id of superman, the following URL's will all hit the</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">http://my.company.com/myapp/movies/superman
http://my.company.com/myapp/movies/superman.xml
http://my.company.com/myapp/movies/superman.xhtml
http://my.company.com/myapp/movies/superman.json
</pre>
</div></div><div class="confluence-information-macro confluence-information-macro-note"><span class="aui-icon aui-icon-small aui-iconfont-warning confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>Note, these content types are supported as incoming data types as well. And, if you need, you can extend the functionality by writing your own implementations of org.apache.struts2.rest.handler.ContentTypeHandler and registering them with the system.</p></div></div><h2 id="RESTPlugin-Usage">Usage</h2><p>This section will walk you through a quick demo. Here are the steps in the sequence that we will follow.</p><ul style="list-style-type: square;"><li>Setting Up your Project</li><li><span style="line-height: 1.4285715;">Configuring your Project</span></li><li><span style="line-height: 1.4285715;">Writing your Controllers</span></li></ul><h3 id="RESTPlugin-SettingUp">Setting Up</h3><p>Assuming you have a normal Struts 2 application, all you need to do for this REST demo is to add the following two plugins:</p><ul style="list-style-type: square;"><li>Struts 2 Rest Plugin</li><li><a shape="rect" class="external-link" href="http://struts.apache.org/2.3.8/docs/convention-plugin.html" style="line-height: 1.4285715;">Struts 2 Convention Plugin</a></li></ul><p>Note, you can download the jars for these plugins from <a shape="rect" class="external-link" href="http://search.maven.org/#search%7Cga%7C1%7Cstruts2-convention-plugin" rel="nofollow">Maven Central</a></p><h4 id="RESTPlugin-Configuration(struts.xml)">Configuration ( <code>struts.xml</code> )</h4><p>Just dropping the plugin's into your application may not produce exactly the desired effect. There are a couple of considerations. The first consideration is whether you want to have any non-RESTful URL's coexisting with your RESTful URL's. We'll show two configurations. The first assumes all you want to do is REST. The second assumes you want to keep other non-RESTful URL's alive in the same Struts 2 application.</p><div class="confluence-information-macro confluence-information-macro-note"><span class="aui-icon aui-icon-small aui-iconfont-warning confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>As with all configuration of Struts 2, we prefer using <code>&lt;constant/&gt;</code> elements in our <code>struts.xml</code>.</p></div></div><h5 id="RESTPlugin-RESTOnlyConfiguration">REST Only Configuration</h5><p>Instruct Struts to use the REST action mapper:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;constant name="struts.mapper.class" value="rest" /&gt;
</pre>
</div></div><p>At this point, the REST mapper has replaced the DefaultActionMapper so all incoming URL's will be interpreted as RESTful URL's.</p><p>We're relying on the Convention plugin to find our controllers, so we need to configure the convention plugin a bit:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;constant name="struts.convention.action.suffix" value="Controller"/&gt;
&lt;constant name="struts.convention.action.mapAllMatches" value="true"/&gt;
&lt;constant name="struts.convention.default.parent.package" value="rest-default"/&gt;
&lt;constant name="struts.convention.package.locators" value="example"/&gt;
</pre>
</div></div><div class="confluence-information-macro confluence-information-macro-note"><span class="aui-icon aui-icon-small aui-iconfont-warning confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>Note, you don't have to use the Convention plugin just to use the REST plugin. The actions of your RESTful application can be defined in XML just as easily as by convention. The REST mapper doesn't care how the application came to know about your actions when it maps a URL to an invocation of one of it's methods.</p></div></div><h5 id="RESTPlugin-RESTandnon-RESTfulURL'sTogetherConfiguration">REST and non-RESTful URL's Together Configuration</h5><p>If you want to keep using some non-RESTful URL's alongside your REST stuff, then you'll have to provide for a configuration that utilizes to mappers.</p><div class="confluence-information-macro confluence-information-macro-note"><span class="aui-icon aui-icon-small aui-iconfont-warning confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>Plugins contain their own configuration. If you look in the Rest plugin jar, you'll see the <code>struts-plugin.xml</code> and in that you'll see some configuration settings made by the plugin. Often, the plugin just sets things the way it wants them. You may frequently need to override those settings in your own <code>struts.xml</code>.</p></div></div><p>First, you'll need to re-assert the extensions that struts knows about because the rest plugin will have thrown out the default <code>action</code> extension.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">  &lt;constant name="struts.action.extension" value="xhtml,,xml,json,action"/&gt;
</pre>
</div></div><p>Next, we will configure the <code>PrefixBasedActionMapper</code>, which is part of the core Struts 2 distribution, to have some URL's routed to the Rest mapper and others to the default mapper.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">  &lt;constant name="struts.mapper.class" value="org.apache.struts2.dispatcher.mapper.PrefixBasedActionMapper" /&gt;
  &lt;constant name="struts.mapper.prefixMapping" value="/rest:rest,:struts"/&gt;
</pre>
</div></div><p>And, again, we're relying on the Convention plugin to find our controllers, so we need to configure the convention plugin a bit:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;constant name="struts.convention.action.suffix" value="Controller"/&gt;
&lt;constant name="struts.convention.action.mapAllMatches" value="true"/&gt;
&lt;constant name="struts.convention.default.parent.package" value="rest-default"/&gt;
&lt;constant name="struts.convention.package.locators" value="example"/&gt;
</pre>
</div></div><h3 id="RESTPlugin-WriteYourControllerActions">Write Your Controller Actions</h3><p>Once everything is configured, you need to create the controllers. Controllers are simply actions created with the purpose of handling requests for a give RESTful resource. As we saw in the mapping logic above, various REST URL's will hit different methods on the controller. Traditionally, normal Struts 2 actions expose the <code>execute</code> method as their target method. Here's a sample controller for a <em>orders</em> resource. Note, this sample doesn't implement all of the methods that can be hit via the RESTful action mapper's interpretation of URL's.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">package org.apache.struts2.rest.example;

public class OrdersController implements ModelDriven&lt;Order&gt; {

    private OrderManager orderManager;
    private String id;
    private Order model;

    // Handles /orders/{id} GET requests
    public HttpHeaders show() {
        model = orderManager.findOrder(id);
        return new DefaultHttpHeaders("show")
            .withETag(model.getUniqueStamp())
            .lastModified(model.getLastModified());
    }

    // Handles /orders/{id} PUT requests
    public String update() {
        orderManager.updateOrder(model);
        return "update";
    }

    // getters and setters
}
</pre>
</div></div><p>In this example, the <code>ModelDriven</code> interface is used to ensure that only my model, the Order object in this case, is returned to the client, otherwise, the whole <code>OrdersController</code> object would be serialized.</p><div class="confluence-information-macro confluence-information-macro-note"><span class="aui-icon aui-icon-small aui-iconfont-warning confluence-information-macro-icon"></span><div class="confluence-information-macro-body"><p>Where's ActionSupport? Normally, you extend ActionSupport when writing Struts 2 actions. In these case, our controller doesn't do that. Why, you ask? ActionSupport provides a bunch of important functionality to our actions, including support for i18n and validation. All of this functionality, in the RESTful case, is provided by the default interceptor stack defined in the REST plugin's struts-plugin.xml file. Unless you willfully break your controller's membership in the rest-default package in which that stack is defined, then you'll get all that functionality you are used to inheriting from ActionSupport.</p></div></div><p>You may wonder why the <code>show()</code> method returns a <code>HttpHeaders</code> object and the <code>update()</code> method returns the expected result code String. The REST Plugin adds support for action methods that return <code>HttpHeaders</code> objects as a way for the action to have more control over the response. In this example, we wanted to ensure the response included the ETag header and a last modified date so that the information will be cached properly by the client. The <code>HttpHeaders</code> object is a convenient way to control the response in a type-safe way.</p><p>Also, notice we aren't returning the usual "success" result code in either method. This allows us to use the special features of the <a shape="rect" href="codebehind-plugin.html">Codebehind Plugin</a> to intuitively select the result template to process when this resource is accessed with the <code>.xhtml</code> extension. In this case, we can provide a customized XHTML view of the resource by creating <code>/orders-show.jsp</code> and <code>/orders-update.jsp</code> for the respective methods.</p><h2 id="RESTPlugin-AdvancedTopics">Advanced Topics</h2><p>The following sections describe some of the non-standard bells and whistles that you might need to utilize for your application's more non-standard requirements.</p><h3 id="RESTPlugin-CustomContentTypeHandlers">Custom ContentTypeHandlers</h3><p>If you need to handle extensions that aren't supported by the default handlers, you can create your own <code>ContentTypeHandler</code> implementation and define it in your <code>struts.xml</code>:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;bean name="yaml" type="org.apache.struts2.rest.handler.ContentTypeHandler" class="com.mycompany.MyYamlContentHandler" /&gt;
</pre>
</div></div><p>If the built-in content type handlers don't do what you need, you can override the handling of any extension by providing an alternate handler. First, define your own <code>ContentTypeHandler</code> and declare with its own alias. For example:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;bean name="myXml" type="org.apache.struts2.rest.handler.ContentTypeHandler" class="com.mycompany.MyXmlContentHandler" /&gt;
</pre>
</div></div><p>Then, tell the REST Plugin to override the handler for the desired extension with yours. In <code>struts.properties</code>, it would look like this:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: java; gutter: false; theme: Default" style="font-size:12px;">struts.rest.handlerOverride.xml=myXml
</pre>
</div></div><h3 id="RESTPlugin-UseJacksonframeworkasJSONContentTypeHandler">Use Jackson framework as JSON ContentTypeHandler</h3><p>The default JSON Content Handler is build on top of the <a shape="rect" class="external-link" href="http://json-lib.sourceforge.net/" rel="nofollow">JSON-lib</a>. If you prefer to use the <a shape="rect" class="external-link" href="http://jackson.codehaus.org/" rel="nofollow">Jackson framework</a> for JSON serialisation, you can configure the JacksonLibHandler as Content Handler for your json requests.&#160;</p><p>First you need to add the jackson dependency to your web application by downloading the jar file and put it under WEB-INF/lib or by adding following xml snippet to your dependencies section in the pom.xml when you are using maven as build system.</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;dependency&gt;
    &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt;
    &lt;artifactId&gt;jackson-jaxrs&lt;/artifactId&gt;
    &lt;version&gt;1.9.13&lt;/version&gt;
&lt;/dependency&gt;
</pre>
</div></div><p>Now you can overwrite the Content Handler with the Jackson Content Handler in the struts.xml:</p><div class="code panel pdl" style="border-width: 1px;"><div class="codeContent panelContent pdl">
<pre class="brush: xml; gutter: false; theme: Default" style="font-size:12px;">&lt;bean type="org.apache.struts2.rest.handler.ContentTypeHandler" name="jackson" class="org.apache.struts2.rest.handler.JacksonLibHandler"/&gt;
&lt;constant name="struts.rest.handlerOverride.json" value="jackson"/&gt;

&lt;!-- Set to false if the json content can be returned for any kind of http method --&gt;
&lt;constant name="struts.rest.content.restrictToGET" value="false"/&gt; 

&lt;!-- Set encoding to UTF-8, default is ISO-8859-1 --&gt;
&lt;constant name="struts.i18n.encoding" value="UTF-8"/&gt; 

</pre>
</div></div><p>&#160;</p><h3 id="RESTPlugin-Settings">Settings</h3><p>The following settings can be customized. See the <a shape="rect" class="external-link" href="http://cwiki.apache.org/confluence/display/WW/Configuration+Files">developer guide</a>.<br clear="none"> For more configuration options see the <a shape="rect" href="convention-plugin.html">Convention Plugin Documentation</a></p><div class="table-wrap"><table class="confluenceTable"><tbody><tr><th colspan="1" rowspan="1" class="confluenceTh"><p>Setting</p></th><th colspan="1" rowspan="1" class="confluenceTh"><p>Description</p></th><th colspan="1" rowspan="1" class="confluenceTh"><p>Default</p></th><th colspan="1" rowspan="1" class="confluenceTh"><p>Possible Values</p></th></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p><code>struts.rest.handlerOverride.EXTENSION</code></p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>The alias for the <code>ContentTypeHandler</code> implementation that handles the EXTENSION value</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>N/A</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Any declared alias for a <code>ContentTypeHandler</code> implementation</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p><code>struts.rest.defaultExtension</code></p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>The default extension to use when none is explicitly specified in the request</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p><code>xhtml</code></p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Any extension</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p><code>struts.rest.validationFailureStatusCode</code></p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>The HTTP status code to return on validation failure</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p><code>400</code></p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Any HTTP status code as an integer</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p><code>struts.rest.namespace</code></p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Optional parameter to specify namespace for REST services</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p><code>/</code></p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>eg. /rest</p></td></tr><tr><td colspan="1" rowspan="1" class="confluenceTd"><p><code>struts.rest.content.restrictToGET</code></p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>Optional parameter, if set to true blocks returning content from any other methods than GET, if set to false, the content can be returned for any kind of method</p></td><td colspan="1" rowspan="1" class="confluenceTd"><p><code>true</code></p></td><td colspan="1" rowspan="1" class="confluenceTd"><p>eg. put struts.rest.content.restrictToGET = false in struts.properties</p></td></tr></tbody></table></div><h2 id="RESTPlugin-Resources">Resources</h2><ul><li><a shape="rect" class="external-link" href="http://www.b-simple.de/documents" rel="nofollow">http://www.b-simple.de/documents</a> - Short RESTful Rails tutorial (PDF, multiple languages)</li><li><a shape="rect" class="external-link" href="http://www.amazon.com/RESTful-Web-Services-Leonard-Richardson/dp/0596529260" rel="nofollow">RESTful Web Services</a> - Highly recommend book from O'Reilly</li><li><a shape="rect" class="external-link" href="http://raibledesigns.com/rd/entry/go_light_with_apache_struts" rel="nofollow">Go Light with Apache Struts 2 and REST</a> - Presentation by Don Brown at ApacheCon US 2008</li></ul><h2 id="RESTPlugin-VersionHistory">Version History</h2><p>From Struts 2.1.1+</p></div>
        </div>

        
    </div>
</div>
<div class="footer">
    Generated by CXF SiteExporter
</div>
</body>
</html>
